package com.example.springboot01.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot01.config.StudentContextHolder;
import com.example.springboot01.config.TeacherContextHolder;
import com.example.springboot01.entity.Course;
import com.example.springboot01.entity.Score;
import com.example.springboot01.entity.Student;
import com.example.springboot01.execs.CustomException;
import com.example.springboot01.mapper.ScoreMapper;
import com.example.springboot01.req.PageQueryReq;
import com.example.springboot01.resp.ScoreDTO;
import com.example.springboot01.resp.StudentScoreResp;
import com.example.springboot01.service.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {


    @Resource
    private ClassService classService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private StudentService studentService;

    @Resource
    private CourseService courseService;

    @Override
    public void addScore(Score score, HttpSession session) {

        final List<Score> list = this.list(new LambdaQueryWrapper<Score>()
                .eq(Score::getTeacherId, TeacherContextHolder.get())
                .eq(Score::getCourseId, score.getCourseId())
                .eq(Score::getStudentId, score.getStudentId())
        );

        if (!CollectionUtils.isEmpty(list)) {
            throw new CustomException(300, "该生本科成绩已录入");
        }

        score.setTeacherId(TeacherContextHolder.get());
        this.save(score);
    }

    @Override
    public IPage<ScoreDTO> getPage(PageQueryReq req, HttpSession session) {
        IPage<Score> temp = new Page<>(req.getCurrent(), req.getSize());

        temp = this.page(temp, new LambdaQueryWrapper<Score>()
                .eq(Score::getTeacherId, TeacherContextHolder.get()));

        IPage<ScoreDTO> result = new Page<>();
        List<ScoreDTO> list = new ArrayList<>();
        BeanUtil.copyProperties(temp, result);
        List<Score> records = temp.getRecords();
        for (Score record : records) {
            ScoreDTO scoreDTO = new ScoreDTO();
            scoreDTO.setId(record.getId());
            scoreDTO.setValue(record.getValue());
            scoreDTO.setStudent(studentService.getById(record.getStudentId()).getRealName());
            scoreDTO.setCourse(courseService.getById(record.getCourseId()).getName());
            scoreDTO.setTeacher(teacherService.getById(record.getTeacherId()).getTeacherNo());
            scoreDTO.setStudentId(record.getStudentId());
            scoreDTO.setCourseId(record.getCourseId());
            list.add(scoreDTO);
        }

        result.setRecords(list);
        return result;
    }

    @Override
    public StudentScoreResp queryScore() {
        final Integer sId = StudentContextHolder.get();
        final Student s = studentService.getById(sId);
        final Integer professorId = s.getProfessorId();
        List<Course> courses = courseService.getByProfessor(professorId);
        StudentScoreResp scoreResp = new StudentScoreResp();
        if (CollectionUtils.isEmpty(courses)) {
            scoreResp.setTableHeader(new ArrayList<>());
            scoreResp.setData(new ArrayList<>());
            return scoreResp;
        }


        List<StudentScoreResp.TableHeader> tableHeaders = new ArrayList<>();
        for (int i = 0; i < courses.size(); i++) {
            Course cours = courses.get(i);
            StudentScoreResp.TableHeader h = new StudentScoreResp.TableHeader();
            h.setLabel(cours.getName());
            h.setProp("col" + cours.getId());
            tableHeaders.add(h);
        }


        scoreResp.setTableHeader(tableHeaders);
        List<Map> data = new ArrayList<>();

        final List<Score> list = this.list(new LambdaQueryWrapper<Score>()
                .eq(Score::getStudentId, sId)
        );
        Map<String, Integer> scoreMap = new HashMap<>();
        for (Course course : courses) {
            for (Score score : list) {
                if (score.getCourseId().equals(course.getId())) {
                    scoreMap.put("col" + course.getId(), score.getValue());
                    break;
                }
            }
        }
        data.add(scoreMap);
        scoreResp.setData(data);
        return scoreResp;
    }
}
